﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DevExpress.Xpf.Core;
using LabelPrint.Models;
using LabelPrint.Util;
using Stimulsoft.Base.Localization;
using Stimulsoft.Report;
using Stimulsoft.Report.CodeDom;


namespace LabelPrint
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : DXWindow
    {
        #region INotifyPropertyChanged Implements
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        } 
        #endregion

        private DateTime _selectDate;
        public DateTime SelectDate
        {
            get { return _selectDate; }
            set
            {
                if (_selectDate != value)
                {
                    _selectDate = value;
                    OnPropertyChanged("SelectDate");
                }
            }
        }

        private string _beginNum;
        public string BeginNum
        {
            get { return string.IsNullOrWhiteSpace(_beginNum) ? "" : _beginNum.Trim(); }
            set
            {
                if (_beginNum != value)
                {
                    _beginNum = value;
                    OnPropertyChanged("BeginNum");
                }
            }
        }

        private string _endNum;

        public string EndNum
        {
            get { return string.IsNullOrWhiteSpace(_endNum) ? "" : _endNum.Trim();  }
            set
            {
                if (_endNum != value)
                {
                    _endNum = value;
                    OnPropertyChanged("EndNum");
                }
            }
        }

        public bool AutoPrint
        {
            get { return _bAutoPrint; }
            set
            {
                if (_bAutoPrint != value)
                {
                    _bAutoPrint = value;
                    OnPropertyChanged("AutoPrint");
                }
            }
        }
        private const string _reportName = "Report.mrt";
        private bool _bAutoPrint = true;
        private bool _bDeamonState = true;
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            SelectDate = DateTime.Now.Date;
            StartBackgroundPrint();
        }

        /// <summary>
        /// 默认后台打印，一旦有新的值就打印
        /// </summary>
        public void StartBackgroundPrint()
        {
            Task.Factory.StartNew(() =>
            {
                var report = new StiReport();
                while (_bDeamonState)
                {
                    if (!AutoPrint)
                    {
                        Thread.Sleep(10000);
                        continue;
                    }
                    var lastCoilName = Coils.GetLastCoilName();
                    var coils = Coils.QueryLatestCoils(lastCoilName);
                    var ci = coils.Select(c => c.CoilName.Replace("_", "")).ToList();
                    if (ci.Count > 0){
                        report.Load(_reportName);
                        //report.DataStore.Clear();
                        report.BusinessObjectsStore.Clear();
                        report.RegBusinessObject("categories", "BarCodeItem", ci);
                        report.Print(false, LocalPrinter.DefaultPrintSettings);
                        Coils.WriteCoilName(ci[0]);
                    }
                    Thread.Sleep(10000);
                }
            });
        }

        private void DXWindow_Loaded(object sender, RoutedEventArgs e)
        {
            DevExpress.Xpf.Core.ThemeManager.ApplicationThemeName = "DeepBlue";
            StiLocalization.Load(@"Localization\zh-CHS.xml");
            //StartBackgroundPrint();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (BeginNum == "" || EndNum == "")
            {
                MessageBox.Show("请输入开始和结束的数字", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            var report = new StiReport();
            report.Load(_reportName);
            report.RegBusinessObject("categories", "BarCodeItem", GenerateList());
            report.ShowWithWpfRibbonGUI();
        }

        public List<Object> GenerateList()
        {
            var begin = 0;
            var end = 0;
            int.TryParse(BeginNum, out begin);
            int.TryParse(EndNum, out end);
            var resultList = new List<object>();
            for (int i = begin; i <= end; i++)
            {
                resultList.Add(new BarCodeItem { BarCode = SelectDate.ToString("yyyyMM") + i.ToString("0000") });
            }
            return resultList;
        }

        public class BarCodeItem
        {
            public string BarCode { get; set; }
        }

        private void DesignButton_OnClick(object sender, RoutedEventArgs e)
        {
            var report = new StiReport();
            if (File.Exists(_reportName))
            {
                report.Load(_reportName);
            }
            report.RegBusinessObject("categories", "BarCodeItem", new BarCodeItem{BarCode = "2014110001"});
            report.Design();
        }

        private void DXWindow_Closing(object sender, CancelEventArgs e)
        {
            _bDeamonState = false;
        }
    }
}
